<script setup lang="ts">
import { postLoginPasswordAPI } from '@/apis/common'
import { useUserStore } from '@/stores/user'
import type { PostLoginPasswordParams } from '@/types/login'
import { ref } from 'vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})
//postLoginPasswordAPI
// 登录
const loginForm = ref<PostLoginPasswordParams>({
  mobile: '13230000019',
  password: 'abc12345',
})
const isAgree = ref(false)
// 登录
const onSubmit = async () => {
  // await formRef.value?.validate?.()
  // const res = await postLoginPasswordAPI(loginForm.value)
  // console.log(res)
  try {
    if (!isAgree.value) {
      uni.showToast({
        title: '请先同意用户协议和隐私协议',
        icon: 'none',
      })
      return
    }
    await formRef.value?.validate?.()
    const res = await postLoginPasswordAPI(loginForm.value)
    const store = useUserStore()
    store.setToken(res.data.token)
    store.setUserInfo(res.data)
    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })
    uni.switchTab({
      url: '/pages/index/index',
    })
  } catch (err) {
    console.log(err)
  }
}
const formRef = ref<UniHelper.UniFormsInstance>()
const formRules = {
  mobile: {
    rules: [
      { required: true, errorMessage: '请填写手机号码' },
      { pattern: /^1\d{10}$/, errorMessage: '手机号码格式不正确' },
    ],
  },
  password: {
    rules: [{ required: true, errorMessage: '请输入密码' }],
  },
}
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :value="loginForm" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="loginForm.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        v-model="loginForm.password"
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" color="#16C2A3" @click="isAgree = !isAgree" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @tap="onSubmit">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
  {{ loginForm }}
</template>

<style lang="scss">
@import './style.scss';
</style>
